<script setup lang="ts">
import { defineProps, ref, watch } from "vue"
import { FormInst, NModal, NForm, NFormItem, NInput, NButton, NSpace } from "naive-ui"

const props = defineProps<{
  showModal: boolean
  modalSubmit: (data: any) => void
  modalClose: () => void
  labelData: any
  handleDeleteLabel: (id: number) => void
}>()

const formRef = ref<FormInst | null>(null)

const dynamicForm = ref({
  vos: [{ tagKey: "", tagValue: "" }],
})

//弹窗确认
const modalOnOk = () => {
  formRef.value?.validate(errors => {
    if (!errors) {
      props.modalSubmit({ orderId: props.labelData?.orderId, ...dynamicForm.value })
      dynamicForm.value = { vos: [{ tagKey: "", tagValue: "" }] }
    }
  })
}
//弹窗关闭
const modalCancel = () => {
  props.modalClose()
  dynamicForm.value = { vos: [{ tagKey: "", tagValue: "" }] }
}

//编辑分类的监听回调
watch(
  () => props.labelData,
  (newValue, oldValue) => {
    dynamicForm.value.vos = newValue.vos.length > 0 ? newValue.vos : [{ tagKey: "", tagValue: "" }]
  },
  {
    deep: true,
  }
)
const removeItem = (index: number) => {
  if (dynamicForm.value.vos[index].id) {
    props.handleDeleteLabel(dynamicForm.value.vos[index]?.id)
  }
  dynamicForm.value.vos?.splice(index, 1)
}

const addItem = () => {
  dynamicForm.value.vos.push({ tagKey: "", tagValue: "" })
}
</script>

<template>
  <div class="modal">
    <n-modal :show="props.showModal" preset="dialog" title="编辑标签" positive-text="确认" negative-text="取消"
      @positive-click="modalOnOk" @negative-click="modalCancel" :show-icon="false" :closable="true" :onClose="modalCancel"
      :on-mask-click="modalCancel">
      <n-form ref="formRef" label-placement="left" label-width="auto" :model="dynamicForm">
        <n-form-item v-for="(item, index) in dynamicForm.vos" :key="index" label="" :path="`vos[${index}]`">
          <n-space :wrap="false">
            <n-input v-model:value="item.tagKey" clearable placeholder="请输入标签名" />
            <n-input v-model:value="item.tagValue" clearable placeholder="请输入标签描述" />
            <n-button v-show="index != 0" style="margin-left: 12px" @click="removeItem(index)">
              删除
            </n-button>
          </n-space>
        </n-form-item>
      </n-form>
      <n-button style="margin-left: 12px" @click="addItem()"> 新增标签 </n-button>
    </n-modal>
  </div>
</template>

<style lang="scss" scoped>
.form_item {
  width: 100px;
}
</style>
